<template>
	<div class="app-container">
		<div class="addBtn">
			<el-row :gutter="10" class="mb8">
				<el-col :span="1.5">
					<el-button type="primary" plain @click="handleAdd"
						v-hasPermi="['residing:roomType:add']">新增房型</el-button>
				</el-col>
			</el-row>
		</div>


		<el-table v-loading="loading" :data="roomTypeList" @selection-change="handleSelectionChange">
			<el-table-column label="序号" align="center" prop="id" />
			<!-- 房间图片列 -->
      <el-table-column label="房间图片" align="center">
        <template #default="scope">
          <div class="photo-group">
            <el-image
                v-if="scope.row.photos"
                :src="scope.row.photos"
                fit="cover"
                style="width: 80px; height: 80px; cursor: pointer;"
                :preview-src-list="[scope.row.photos]"
                :preview-teleported="true"
            />
            <div v-else>暂无图片</div>
          </div>
        </template>
      </el-table-column>
			<el-table-column label="房间类型" align="center" prop="name" />
			<el-table-column label="床位费用" align="center" prop="bedFee">
				<template #default="scope">
					{{
		        scope.row.bedFee.toFixed(2)
		      }}
				</template>
			</el-table-column>
			<el-table-column label="创建人" align="center" prop="createdBy" />
			<el-table-column label="房型介绍" align="center" prop="description" width="200px" />
			<el-table-column label="创建时间" align="center" prop="createdAt" width="180">
				<template #default="scope">
					<span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="状态" align="center">
				<template #default="scope">
					<!-- 用el-tag渲染状态，通过方法动态控制类型和文字 -->
					<el-tag :type="getStatusTagType(scope.row.status)" class="custom-tag">
						{{ getStatusText(scope.row.status) }}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160px">
				<template #default="scope">
					<el-button link type="danger" @click="handleDelete(scope.row)"
						v-hasPermi="['residing:roomType:remove']">删除</el-button>
					<el-button link type="primary" @click="handleUpdate(scope.row)"
						v-hasPermi="['residing:roomType:edit']">编辑</el-button>
					<el-button v-if="scope.row.status === '1'" link type="danger"
						@click="handleUpdateStatus(scope.row.id,scope.row.status)"
						v-hasPermi="['residing:roomType:edit']">禁用</el-button>
					<el-button v-else link type="primary" @click="handleUpdateStatus(scope.row.id,scope.row.status)"
						v-hasPermi="['residing:roomType:edit']">启用</el-button>

				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改房型设置对话框 -->
		<el-dialog :title="title" v-model="open" width="500px" append-to-body>
			<el-form ref="roomTypeRef" :model="form" :rules="rules" label-width="80px">
				<!-- 房型类型（原房间类型） -->
				<el-form-item label="房型类型" prop="name" required>
					<el-input v-model="form.name" placeholder="请输入房型类型" maxlength="10" show-word-limit />
				</el-form-item>

				<!-- 床位费用（改为数字输入框并保留两位小数） -->
				<el-form-item label="床位费用" prop="bedFee" required>
					<el-input-number v-model="form.bedFee" placeholder="请输入床位费用" :min="0" :precision="2" :step="100"
						controls-position="right" style="width: 100%" />
				</el-form-item>
				
				<!-- 床位数量 -->
				<el-form-item label="床位数量" prop="bedCount" required>
					<el-input-number v-model="form.bedCount" placeholder="请输入床位数量" :min="0" :step="1"
						controls-position="right" style="width: 100%" />
				</el-form-item>

				<!-- 新增：状态选择 -->
				<el-form-item label="状态" prop="status" required>
					<el-radio-group v-model="form.status">
						<el-radio :label="'1'">启用</el-radio>
						<el-radio :label="'0'">禁用</el-radio>
					</el-radio-group>
				</el-form-item>

				<!-- 新增：房型图片上传 -->
				<el-form-item label="房型图片" prop="photos">
					<el-upload 
						:headers="{ Authorization: 'Bearer ' + getToken() }" 
						class="avatar-uploader"
						action="/dev-api/common/upload" :show-file-list="false" :on-success="handleAvatarSuccess"
						:before-upload="beforeAvatarUpload">
						<img v-if="form.photos" :src="form.photos" class="avatar" />
						<el-icon v-else class="avatar-uploader-icon">
							<Plus />
						</el-icon>
					</el-upload>
					<div class="text-xs text-gray-500 mt-1">
						支持JPG、PNG格式，文件大小不超过2MB
					</div>
				</el-form-item>

				<!-- 房型介绍 -->
				<el-form-item label="房型介绍" prop="description">
					<el-input v-model="form.description" type="textarea" placeholder="请输入房型介绍" maxlength="200"
						show-word-limit :rows="3" />
				</el-form-item>

				<!-- 备注 -->
				<el-form-item label="备注" prop="remark">
					<el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" maxlength="500"
						show-word-limit :rows="2" />
				</el-form-item>
			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<!-- 调整按钮顺序：取消在前，确定在后 -->
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submitForm">确 定</el-button>
				</div>
			</template>
		</el-dialog>


	</div>
</template>

<script setup name="RoomType">
	import {
		listRoomType,
		getRoomType,
		delRoomType,
		addRoomType,
		updateRoomType,
		updateRoomStatus
	} from "@/api/residing/roomType"

	import { getToken } from '@/utils/auth'


	const {
		proxy
	} = getCurrentInstance()

	const roomTypeList = ref([])
	const open = ref(false)
	const loading = ref(true)
	const showSearch = ref(true)
	const ids = ref([])
	const single = ref(true)
	const multiple = ref(true)
	const total = ref(0)
	const title = ref("")
	const imageUrl = ref('')

	const data = reactive({
		form: {
			name: '', // 房型类型
			bedFee: 0.00, // 床位费用（默认两位小数）
			bedCount: 0, //床位数量
			status: 1, // 状态（1-启用，0-禁用）
			photos: '', // 房型图片URL
			description: '', // 房型介绍
			remark: '', // 备注
		},
		queryParams: {
			pageNum: 1,
			pageSize: 10,
		},
		rules: {
			name: [{
					required: true,
					message: '请输入房型类型',
					trigger: 'blur'
				},
				{
					max: 10,
					message: '房型类型不能超过10个字符',
					trigger: 'blur'
				}
			],
			bedFee: [{
					required: true,
					message: '请输入床位费用',
					trigger: 'blur'
				},
				{
					type: 'number',
					message: '请输入有效的数字',
					trigger: 'blur'
				}
			],
			bedCount: [{
					required: true,
					message: '请输入床位数量',
					trigger: 'blur'
				},
				{
				    validator: (rule, value, callback) => {
				      // 步骤1：判断是否为有效数字（包括字符串/数字形式）
				      if (isNaN(Number(value))) {
				        callback(new Error('请输入有效的数字'));
				      } else {
				        // 步骤2：判断是否为整数（余数为 0）
				        if (Number(value) % 1 !== 0) {
				          callback(new Error('请输入整数'));
				        } else {
				          callback(); // 校验通过
				        }
				      }
				    },
				    trigger: 'blur'
				  }
			],
			status: [{
				required: true,
				message: '请选择状态',
				trigger: 'change'
			}]
		}
	})

	const {
		queryParams,
		form,
		rules
	} = toRefs(data)

	/** 查询房型设置列表 */
	function getList() {
		loading.value = true
		listRoomType(queryParams.value).then(response => {
			console.log(response.rows)
			roomTypeList.value = response.rows
			roomTypeList.value.forEach(item => {
			  // 若 photos 是带首尾引号的字符串，先去除引号
			  if (typeof item.photos === 'string' && item.photos.startsWith('"') && item.photos.endsWith('"')) {
			    item.photos = item.photos.slice(1, -1); // 截取掉首尾的引号
			  }
			
			  // （可选）再做其他格式化，比如校验是否为有效OSS URL
			  const isOssUrl = typeof item.photos === 'string' && 
			                   item.photos.startsWith('https://') && 
			                   item.photos.includes('oss-cn-') && 
			                   item.photos.includes('aliyuncs.com');
			  if (!isOssUrl) {
			    console.warn('无效的OSS图片URL：', item.photos);
			    // 可选择设置默认图或空值，示例：
			    // item.photos = 'https://默认图地址.jpg'; 
			  }
			});
			total.value = response.total
			loading.value = false
		})
	}

	// 取消按钮
	function cancel() {
		open.value = false
		reset()
	}

	// 表单重置
	function reset() {
		form.value = {
			id: null,
			photos: null,
			name: null,
			bedFee: null,
			bedCount: null,
			createdBy: null,
			description: null,
			createdAt: null,
			status: null,
			updatedAt: null,
			updatedBy: null,
			remark: null,
			extend1: null,
			extend2: null
		}
		proxy.resetForm("roomTypeRef")
	}

	/** 搜索按钮操作 */
	function handleQuery() {
		queryParams.value.pageNum = 1
		getList()
	}

	/** 重置按钮操作 */
	function resetQuery() {
		proxy.resetForm("queryRef")
		handleQuery()
	}

	// 多选框选中数据
	function handleSelectionChange(selection) {
		ids.value = selection.map(item => item.id)
		single.value = selection.length != 1
		multiple.value = !selection.length
	}

	/** 新增按钮操作 */
	function handleAdd() {
		reset()
		open.value = true
		title.value = "添加房型设置"
	}

	/** 修改按钮操作 */
	function handleUpdate(row) {
		reset()
		const _id = row.id || ids.value
		getRoomType(_id).then(response => {
			form.value = response.data
			form.value.photos = removeSurroundingQuotes(response.data.photos)
			form.value.bedFee = Number(response.data.bedFee);
			open.value = true
			title.value = "修改房型设置"
		})
	}
	
	// 格式化图片url
	const removeSurroundingQuotes = (str) => {
	  // 检查是否为字符串且首尾都是双引号
	  if (typeof str === 'string' && str.startsWith('"') && str.endsWith('"')) {
	    // 截取从第1位到倒数第2位（去除首尾引号）
	    return str.slice(1, -1);
	  }
	  // 不符合条件时返回原字符串
	  return str;
	};

	/** 删除按钮操作 */
	function handleDelete(row) {
		const _ids = row.id || ids.value
		proxy.$modal.confirm('是否确认删除房型设置编号为"' + _ids + '"的数据项？').then(function() {
			return delRoomType(_ids)
		}).then(() => {
			getList()
			proxy.$modal.msgSuccess("删除成功")
		}).catch(() => {})
	}

	getList()


	const getStatusTagType = (status) => {
		switch (status) {
			case '0':
				return "danger"; // 禁用
			case '1':
				return "success"; // 启用（绿色标签）
			default:
				return "";
		}
	};

	// 方法2：状态值 → 显示文字
	const getStatusText = (status) => {
		switch (status) {
			case '0':
				return "禁用";
			case '1':
				return "启用";
			default:
				return "未知状态";
		}
	};

	async function handleUpdateStatus(id, status) {
		if (status === '0') {
			await updateRoomStatus(id, 1)
		} else {
			await updateRoomStatus(id, 0)
		}
		getList()
	}

	// 图片上传成功回调函数
	const handleAvatarSuccess = (response, uploadFile) => {
		form.value.photos = response.url;
	}

	// 移除UploadProps['beforeUpload']类型标注
	const beforeAvatarUpload = (rawFile) => {
		const validTypes = ['image/jpeg', 'image/png']
		if (!validTypes.includes(rawFile.type)) {
			ElMessage.error('Avatar picture must be JPG/PNG format!')
			return false
		} else if (rawFile.size / 1024 / 1024 > 2) {
			ElMessage.error('Avatar picture size can not exceed 2MB!')
			return false
		}
		return true
	}

	/** 提交按钮 */
	function submitForm() {
		if(!(form.value.photos.startsWith('"') && form.value.photos.endsWith('"'))){
			form.value.photos = JSON.stringify(form.value.photos)
		}
		proxy.$refs["roomTypeRef"].validate(valid => {
			if (valid) {
				if (form.value.id != null) {
					updateRoomType(form.value).then(response => {
						proxy.$modal.msgSuccess("修改成功")
						open.value = false
						getList()
					})
				} else {
					addRoomType(form.value).then(response => {
						proxy.$modal.msgSuccess("新增成功")
						open.value = false
						getList()
					})
				}
			}
		})
	}


	// 暴露给父组件的方法（如需外部控制对话框）
	defineExpose({
		// 示例：打开对话框并设置标题
		openDialog: (dialogTitle) => {
			title.value = dialogTitle;
			open.value = true;
		}
	});
</script>

<style scoped>
	.addBtn {
		display: flex;
		justify-content: flex-end;
		margin-top: 5px;
		margin-bottom: 15px;
	}

	.custom-tag {
		font-size: 12px;
		/* 调整字体大小 */
		padding: 15px 15px;
		/* 调整内边距（上下、左右） */
	}

	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>

<style>
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}
</style>